package WeiXinPayV3;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jdom.JDOMException;

public class WeiXin {

	/** APP_ID 应用从官方网站申请到的合法appId */
	public static final String WX_APP_ID = "wx3e72f605d826f88e";

	/** 商户号 */
	public static final String WX_PARTNER_ID = "1423259202";

	/** 接口链接 */
	public static final String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

	/** 商户平台和开发平台约定的API密钥，在商户平台设置 */
	public static final String key = "shaokezzweibangkeji2016121615000";

	/** 异步回调地址 */
	public static final String notify_url = "http://rtfp3u.natappfree.cc/app/order/notify";

	public StringBuffer wechatPaySb = new StringBuffer();

	// 封装产品信息
	public String getproduct(String money, String out_trade_no) {
		StringBuffer xml = new StringBuffer();
		String nonceStr = genNonceStr();
		xml.append("</xml>");
		List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
		packageParams.add(new BasicNameValuePair("appid", WX_APP_ID));
	//	String money2 = Double.parseDouble(money) * 100 + "";
		// body为汉字是要转成UTF-8
		String name = "buy";
		try {
			name = URLEncoder.encode("商城支付", "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		packageParams.add(new BasicNameValuePair("body", name));
		packageParams.add(new BasicNameValuePair("input_charset", "UTF-8"));
		packageParams.add(new BasicNameValuePair("mch_id", WX_PARTNER_ID));
		packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
		packageParams.add(new BasicNameValuePair("notify_url", notify_url));// "http://121.40.35.3/test"
		packageParams.add(new BasicNameValuePair("out_trade_no", out_trade_no));
		packageParams.add(new BasicNameValuePair("spbill_create_ip",
				"127.0.0.1"));
		packageParams.add(new BasicNameValuePair("total_fee", money));// "" +
																		// (int)(1
																		// *
																		// 100)//money
		packageParams.add(new BasicNameValuePair("trade_type", "APP"));
		String sign = genPackageSign(packageParams);
		packageParams.add(new BasicNameValuePair("sign", sign));
		String xmlstring = toXml(packageParams);
		// try {
		// xmlstring= new String(xmlstring.toString().getBytes(), "ISO8859-1");
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }
		return xmlstring;

	}

	// 获取随机验证参数
	public String genNonceStr() {
		Random random = new Random();
		return MD5Util.getMessageDigest(String.valueOf(random.nextInt(10000))
				.getBytes());
	}

	// 获取包签名
	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(key);
		String packageSign = MD5Util.getMessageDigest(sb.toString().getBytes())
				.toUpperCase();
		System.out.println("包签名：=" + packageSign);
		return packageSign;
	}

	/**
	 * 获得app前面
	 * 
	 * @param params
	 *            参数
	 * @return 签名以后的字符串
	 */
	@SuppressWarnings("unused")
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(key);
		// this.wechatPaySb.append("sign str\n" + sb.toString() + "\n\n");
		String appSign = MD5Util.getMessageDigest(sb.toString().getBytes())
				.toUpperCase();
		System.out.println("APP签名=" + appSign);
		return appSign;
	}

	/**
	 * 将请求参数转换为xml格式
	 * 
	 * @param params
	 *            参数list
	 * @return xml字符串
	 */
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<" + params.get(i).getName() + ">");
			sb.append(params.get(i).getValue());
			sb.append("</" + params.get(i).getName() + ">");
		}
		sb.append("</xml>");
		return sb.toString();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map doInBackground(String money, String out_trade_no) {
		String url = String
				.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
		String entity = getproduct(money, out_trade_no);
		// System.out.println("entity:" + entity);
		String buf = HttpUtil.sendPostUrl(url, entity);
		String content = new String(buf);
		// System.out.println("orion:" + content);
		Map<String, String> xml = null;
		try {
			xml = XMLUtil.doXMLParse(content);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(xml.toString());
		return xml;
	}

	/**
	 * 解析反馈xml数据
	 * 
	 * @param content
	 *            反馈内容
	 * @return 解析结果map
	 */
	// public Map<String,String> decodeXml(String content) {
	// try {
	// Map<String, String> xml = new HashMap<String, String>();
	// XmlPullParser parser = Xml.newPullParser();
	// parser.setInput(new StringReader(content));
	// int event = parser.getEventType();
	// while (event != XmlPullParser.END_DOCUMENT) {
	// String nodeName=parser.getName();
	// switch (event) {
	// case XmlPullParser.START_DOCUMENT:
	//
	// break;
	// case XmlPullParser.START_TAG:
	// if("xml".equals(nodeName)==false){
	// //实例化student对象
	// xml.put(nodeName,parser.nextText());
	// }
	// break;
	// case XmlPullParser.END_TAG:
	// break;
	// }
	// event = parser.next();
	// }
	// return xml;
	// } catch (Exception e) {
	// // e.printStackTrace();
	// }
	// return null;
	// }
	/**
	 * 微信支付签名算法sign
	 * 
	 * @param characterEncoding
	 * @param parameters
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public static String createSign(String characterEncoding,
			SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + key);
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding)
				.toUpperCase();
		return sign;
	}

	public String getTimeStamp() {
		// return String.valueOf(System.currentTimeMillis() /
		// 1000)+MathUtil.randomFour() ;
		return String.valueOf(System.currentTimeMillis() / 1000);
	}

	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {
		WeiXin wx = new WeiXin();
		Map xml;
		try {
			xml = wx.doInBackground("161", "2222222222222");
			System.out.println(xml.get("prepay_id"));
			System.out.println(xml.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
